package com.github.willisaway.core.util;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.github.willisaway.core.annotation.AviatorFunctionScan;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.type.AviatorFunction;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AviatorUtil {
    public static void addFunctions() {
        Map<String, Object> functionsMap = SpringUtil.getApplicationContext()
                .getBeansWithAnnotation(AviatorFunctionScan.class);
        for (Map.Entry<String, Object> entry : functionsMap.entrySet()) {
            AviatorEvaluator.addFunction((AviatorFunction) entry.getValue());
        }
    }

    public static Object execute(String expression, Map<String, Object> env) {
        Object obj = null;
        try {
            obj = AviatorEvaluator.execute(expression, env, true);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(ExceptionUtil.getStackTraceAsString(e));
        }
        return obj;
    }

    public static Object execute(String expression, Map<String, Object> env, String alias) {
        Object obj = null;
        try {
            if (StringUtils.isNotBlank(alias)) {
                env.put("alias", alias);
            }
            obj = AviatorEvaluator.execute(expression, env, true);
        } catch (Exception e) {
            log.error("表达式执行错误" + expression);
            e.printStackTrace();
            log.error(ExceptionUtil.getStackTraceAsString(e));
        }
        return obj;
    }
}
